# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        def advance(head, n):
            while head and n>0:
                head = head.next
                n -= 1
            return head

        def getLength(head):
            length = 0
            while head:
                head = head.next
                length+=1
            return length

        newHead = ListNode(None)
        newHead.next = head

        length = getLength(head)
        nth = length+1-n
        tail = advance(newHead, nth-1)
        tail.next = tail.next.next
        return newHead.next